import Vuex from 'vuex';
import Vue from 'vue';
import VuexPersist from 'vuex-persist'
import flowerList from './flowerList'
import categoryList from './categoryList'
Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        //初始化store
        flowerList: flowerList,
        categoryList: categoryList,
        flower: {},
        cart: []
    },
    mutations: {
        //更新当前选中的花卉
        DETAIL(state, flower) {
            state.flower = flower;
        },
        //向购物车添加商品。如果购物车为空或商品已存在，则更新数量；否则，添加新商品。
        ADDCART(state, flower) {
            if (state.cart.length == 0) {
                Vue.set(flower, 'number', 1)
                state.cart.push(flower)
                return;
            }
            for (let index = 0; index < state.cart.length; index++) {
                if (state.cart[index].flowerName == flower.flowerName) {
                    state.cart[index].number++;
                    return;
                }
            }
            Vue.set(flower, 'number', 1)
            state.cart.push(flower)
        },
        //增加
        ADD(state, flower) {
            state.cart.forEach((item) => {
                if (item.flowerName == flower.flowerName) item.number++;
            })
        },
        //减少
        SUB(state, flower) {
            state.cart.forEach((item) => {
                if (item.flowerName == flower.flowerName) item.number--;
            })
        },
        //删除
        DELETE(state, flower) {
            state.cart = state.cart.filter((item) => {
                if (item.flowerName != flower.flowerName) return true;
            })
        },
        //支付
        PAY(state, selectflower) {
            state.cart = state.cart.filter((item) => {
                let flag = false;
                for (let index = 0; index < selectflower.length; index++) {
                    if (item.flowerName == selectflower[index].flowerName) {
                        flag = true;
                        break;
                    }
                }
                if (flag) return false;
                else return true;
            })
        },
        //清空购物车
        CLEAR(state) {
            state.cart = [];
        }
    },
    plugins: [
        //应用的状态可以在页面刷新后恢复
        new VuexPersist({
            storage: window.localStorage,
        }).plugin,
    ]
})